<template>
  <div class="contest-review-container">
    <div class="page-header">
      <h2>竞赛审核</h2>
      <div class="header-actions">
        <div class="filter-container">
          <el-input
            v-model="searchQuery"
            placeholder="搜索竞赛标题"
            class="filter-item"
            :prefix-icon="Search"
            @input="handleSearch"
            clearable
          />
          <el-select
            v-model="statusFilter"
            placeholder="状态筛选"
            class="filter-item"
            @change="handleFilter"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
      </div>
    </div>

    <el-card shadow="hover" class="list-card">
      <el-table
        v-loading="loading"
        :data="contestList"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="title" label="竞赛标题" min-width="200">
          <template #default="scope">
            <el-link type="primary" @click="viewDetail(scope.row.id)">
              {{ scope.row.title }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="creatorName" label="创建者" width="120" align="center" />
        <el-table-column prop="startTime" label="开始时间" width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="160" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="currentParticipants" label="参与人数" width="100" align="center" />
        <el-table-column prop="status" label="状态" width="120" align="center">
          <template #default="scope">
            <el-tag
              :type="getStatusType(scope.row.status)"
              :effect="getStatusEffect(scope.row.status)"
              round
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="viewDetail(scope.row.id)"
            >
              查看
            </el-button>
            <el-button
              v-if="scope.row.status === 0"
              type="success"
              link
              @click="approveContest(scope.row.id)"
            >
              通过
            </el-button>
            <el-button
              v-if="scope.row.status === 0"
              type="danger"
              link
              @click="rejectContest(scope.row.id)"
            >
              拒绝
            </el-button>
            <el-button
              v-if="scope.row.status === 1"
              type="warning"
              link
              @click="endContest(scope.row.id)"
            >
              结束
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="竞赛详情"
      width="70%"
    >
      <div v-if="currentContest" class="contest-detail">
        <div class="detail-header">
          <h3>{{ currentContest.title }}</h3>
          <el-tag
            :type="getStatusType(currentContest.status)"
            :effect="getStatusEffect(currentContest.status)"
            round
          >
            {{ getStatusText(currentContest.status) }}
          </el-tag>
        </div>

        <div class="detail-info">
          <div class="info-item">
            <span class="label">创建者：</span>
            <span>{{ currentContest.creatorName }}</span>
          </div>
          <div class="info-item">
            <span class="label">开始时间：</span>
            <span>{{ formatDateTime(currentContest.startTime) }}</span>
          </div>
          <div class="info-item">
            <span class="label">结束时间：</span>
            <span>{{ formatDateTime(currentContest.endTime) }}</span>
          </div>
          <div class="info-item">
            <span class="label">参与人数：</span>
            <span>{{ currentContest.currentParticipants }} / {{ currentContest.participantLimit || '不限' }}</span>
          </div>
          <div class="info-item">
            <span class="label">颁发证书：</span>
            <span>{{ currentContest.certificateEnabled ? `是 (前 ${currentContest.certificateCount} 名)` : '否' }}</span>
          </div>
        </div>

        <div class="detail-cover">
          <el-image
            :src="currentContest.coverImage"
            fit="cover"
            :preview-src-list="[currentContest.coverImage]"
            class="cover-image"
          >
            <template #error>
              <div class="image-placeholder">无封面图片</div>
            </template>
          </el-image>
        </div>

        <div class="detail-description">
          <h4>竞赛描述</h4>
          <p>{{ currentContest.description }}</p>
        </div>

        <div v-if="currentContest.status === 0" class="detail-actions">
          <el-button type="success" @click="approveContest(currentContest.id)">通过审核</el-button>
          <el-button type="danger" @click="rejectContest(currentContest.id)">拒绝审核</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { 
  getContestList, 
  getContestDetail, 
  endContest as endContestApi,
  reviewContest
} from '@/api/contest'

const loading = ref(false)
const contestList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const statusFilter = ref('')
const detailDialogVisible = ref(false)
const currentContest = ref(null)

// 状态选项
const statusOptions = [
  { value: '', label: '全部状态' },
  { value: '0', label: '待审核' },
  { value: '1', label: '进行中' },
  { value: '2', label: '已拒绝' },
  { value: '3', label: '已取消' },
  { value: '4', label: '已结束' }
]

// 获取竞赛列表
const fetchContestList = async () => {
  loading.value = true
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      keyword: searchQuery.value,
      status: statusFilter.value
    }
    const res = await getContestList(params)
    contestList.value = res.data.records
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取竞赛列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 查看竞赛详情
const viewDetail = async (id) => {
  try {
    const res = await getContestDetail(id)
    currentContest.value = res.data
    detailDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取竞赛详情失败')
    console.error(error)
  }
}

// 通过竞赛审核
const approveContest = (id) => {
  ElMessageBox.confirm(
    '确定要通过此竞赛的审核吗？',
    '审核确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(async () => {
    try {
      // 获取当前用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      if (!userInfo.id) {
        ElMessage.warning('无法获取审核人信息')
        return
      }
      
      // 调用审核API
      await reviewContest(id, 1, userInfo.id)
      ElMessage.success('审核通过')
      fetchContestList()
      if (detailDialogVisible.value) {
        detailDialogVisible.value = false
      }
    } catch (error) {
      ElMessage.error('操作失败')
      console.error(error)
    }
  }).catch(() => {})
}

// 拒绝竞赛审核
const rejectContest = (id) => {
  ElMessageBox.confirm(
    '确定要拒绝此竞赛的审核吗？',
    '审核确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      // 获取当前用户信息
      const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
      if (!userInfo.id) {
        ElMessage.warning('无法获取审核人信息')
        return
      }
      
      // 调用审核API
      await reviewContest(id, 2, userInfo.id)
      ElMessage.success('已拒绝审核')
      fetchContestList()
      if (detailDialogVisible.value) {
        detailDialogVisible.value = false
      }
    } catch (error) {
      ElMessage.error('操作失败')
      console.error(error)
    }
  }).catch(() => {})
}

// 结束竞赛
const endContest = (id) => {
  ElMessageBox.confirm(
    '确定要结束此竞赛吗？',
    '操作确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await endContestApi(id)
      ElMessage.success('竞赛已结束')
      fetchContestList()
    } catch (error) {
      ElMessage.error('操作失败')
      console.error(error)
    }
  }).catch(() => {})
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchContestList()
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
  fetchContestList()
}

// 页面大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchContestList()
}

// 页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchContestList()
}

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '未设置'
  const date = new Date(dateString)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    0: 'info',    // 待审核
    1: 'success', // 进行中
    2: 'danger',  // 已拒绝
    3: 'warning', // 已取消
    4: 'primary'  // 已结束
  }
  return types[status] || 'info'
}

// 获取状态效果
const getStatusEffect = (status) => {
  return status === 1 ? 'light' : 'plain'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    0: '待审核',
    1: '进行中',
    2: '已拒绝',
    3: '已取消',
    4: '已结束'
  }
  return texts[status] || '未知'
}

onMounted(() => {
  fetchContestList()
})
</script>

<style lang="scss" scoped>
.contest-review-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 24px;
      font-weight: 600;
      color: #303133;
    }
    
    .header-actions {
      display: flex;
      gap: 15px;
      
      .filter-container {
        display: flex;
        gap: 10px;
        
        .filter-item {
          width: 200px;
        }
      }
    }
  }
  
  .list-card {
    margin-bottom: 20px;
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  .contest-detail {
    .detail-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      
      h3 {
        margin: 0;
        font-size: 20px;
        color: #303133;
      }
    }
    
    .detail-info {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: 15px;
      margin-bottom: 20px;
      
      .info-item {
        display: flex;
        align-items: center;
        
        .label {
          color: #909399;
          width: 90px;
        }
      }
    }
    
    .detail-cover {
      margin-bottom: 20px;
      
      .cover-image {
        width: 100%;
        max-height: 250px;
        object-fit: cover;
        border-radius: 8px;
      }
      
      .image-placeholder {
        width: 100%;
        height: 150px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #f5f7fa;
        color: #909399;
        border-radius: 8px;
      }
    }
    
    .detail-description {
      margin-bottom: 20px;
      
      h4 {
        margin-top: 0;
        margin-bottom: 10px;
        color: #303133;
      }
      
      p {
        margin: 0;
        color: #606266;
        line-height: 1.6;
        white-space: pre-line;
      }
    }
    
    .detail-actions {
      display: flex;
      justify-content: center;
      gap: 20px;
      margin-top: 30px;
    }
  }
}
</style> 